<template>
  <div class="admin-users-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>用户管理</h1>
        <div class="breadcrumb">
          <span>首页</span> / <span>系统管理</span> / <span class="current">用户管理</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showAddUserDialog">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
        <el-button @click="refreshUserList">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-card">
      <!-- 批量操作工具栏 -->
      <div class="batch-operations">
        <el-tag size="large" effect="dark">{{ selectedRows.length }} 项已选中</el-tag>
        <el-button type="primary" @click="handleBatchChangeStatus('1')">
          <Check class="el-icon--left" />
          批量启用
        </el-button>
        <el-button type="warning" @click="handleBatchChangeStatus('0')">
          <Close class="el-icon--left" />
          批量禁用
        </el-button>
        <el-button type="danger" @click="handleBatchDeleteUsers">
          <Delete class="el-icon--left" />
          批量删除
        </el-button>
        <el-button @click="clearSelection">
          清空选择
        </el-button>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form responsive-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.roleId" placeholder="选择角色" clearable>
            <el-option label="普通用户" value="1" />
            <el-option label="管理员" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearchUsers">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-wrapper">
      <div class="data-table-card">
      <!-- 自定义表格 -->
      <div class="custom-table-wrapper">
        <!-- 表头 -->
        <div class="custom-table-header">
          <div class="custom-table-row">
            <div class="custom-table-cell selection" style="width: 60px;">
              <input 
                type="checkbox" 
                class="select-all-checkbox" 
                :checked="isAllSelected" 
                @change="handleSelectAll"
              />
            </div>
            <div class="custom-table-cell" style="width: 80px;">序号</div>
            <div class="custom-table-cell" style="width: 120px;">角色</div>
            <div class="custom-table-cell" style="width: 240px;">用户名</div>
            <div class="custom-table-cell" style="width: 220px;">账号</div>
            <div class="custom-table-cell email hidden-mobile" style="width: 200px;">邮箱</div>
            <div class="custom-table-cell" style="width: 100px;">状态</div>
            <div class="custom-table-cell last-login-time hidden-mobile" style="width: 180px;">上次登录时间</div>
            <div class="custom-table-cell operation" style="width: 300px;">操作</div>
          </div>
        </div>
        
        <!-- 表格内容区 -->
        <div class="custom-table-body">
          <!-- 使用safeUserList确保安全访问 -->
          <div 
            v-for="(row, index) in safeUserList" 
            :key="row && row.id ? row.id : `row-${index}`" 
            class="custom-table-row"
            :class="{ 'selected': row && isRowSelected(row.id) }"
          >
            <!-- 确保row存在 -->
            <template v-if="row">
              <div class="custom-table-cell selection" style="width: 60px;">
                <input 
                  type="checkbox" 
                  class="row-checkbox" 
                  :checked="isRowSelected(row.id)" 
                  @change="handleRowSelect(row)"
                />
              </div>
              <div class="custom-table-cell" style="width: 80px;">{{ index + 1 }}</div>
              <div class="custom-table-cell" style="width: 120px;">
                <span :class="['role-tag', { 'admin': row.roleId === 2, 'user': row.roleId === 1 }]">
                  {{ row.roleId === 2 ? '管理员' : '普通用户' }}
                </span>
              </div>
              <div class="custom-table-cell" style="width: 240px;">{{ row.username || '-' }}</div>
              <div class="custom-table-cell" style="width: 220px;">{{ row.uid || '-' }}</div>
              <div class="custom-table-cell email hidden-mobile" style="width: 200px;">{{ row.email || '-' }}</div>
              <div class="custom-table-cell" style="width: 100px;">
                <label class="switch">
                  <input 
                    type="checkbox" 
                    :checked="row.status === '1'" 
                    @change="(e) => handleUpdateUserStatus(row.id, e.target.checked ? '1' : '0')"
                  />
                  <span class="slider"></span>
                </label>
              </div>
              <div class="custom-table-cell last-login-time hidden-mobile" style="width: 180px;">{{ formatDate(row.lastLoginTime) }}</div>
              <div class="custom-table-cell operation" style="width: 300px;">
                <div class="operation-buttons">
                  <button type="button" class="btn btn-primary btn-small btn-detail" @click="showUserDetail(row)">
                    <User class="btn-icon" /> 详情
                  </button>
                  <button type="button" class="btn btn-success btn-small btn-reset" @click="showResetPasswordDialog(row)">
                    <Key class="btn-icon" /> 重置密码
                  </button>
                  <button type="button" class="btn btn-primary btn-small btn-edit" @click="showEditUserDialog(row)">
                    <Edit class="btn-icon" /> 编辑
                  </button>
                  <button type="button" class="btn btn-danger btn-small btn-delete" @click="handleDeleteUser(row.id)">
                    <Delete class="btn-icon" /> 删除
                  </button>
                </div>
              </div>
            </template>
          </div>
          
          <!-- 空状态 -->
          <div v-if="safeUserList.length === 0" class="empty-state">
            <p>暂无数据</p>
          </div>
        </div>
      </div>

      <!-- 自定义分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ total }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
        </div>
        <div class="custom-pagination">
          <!-- 页码大小选择 -->
          <div class="page-size-selector">
            <span>每页显示：</span>
            <select v-model="pageSize" @change="handleSizeChange" class="page-size-select">
              <option :value="10">10条</option>
              <option :value="20">20条</option>
              <option :value="50">50条</option>
              <option :value="100">100条</option>
            </select>
          </div>
          
          <!-- 分页按钮 -->
          <div class="pagination-buttons">
            <!-- 上一页 -->
            <button 
              type="button" 
              class="page-btn page-prev" 
              :disabled="currentPage <= 1"
              @click="goToPreviousPage"
            >
              上一页
            </button>
            
            <!-- 页码按钮 -->
            <div class="page-numbers">
              <!-- 生成页码按钮 -->
              <template v-for="page in generatePageNumbers()" :key="page">
                <button 
                  v-if="page === '...'" 
                  type="button" 
                  class="page-btn page-ellipsis"
                  disabled
                >
                  {{ page }}
                </button>
                <button 
                  v-else 
                  type="button" 
                  class="page-btn"
                  :class="{ 'active': page === currentPage }"
                  @click="goToPage(page)"
                >
                  {{ page }}
                </button>
              </template>
            </div>
            
            <!-- 下一页 -->
            <button 
              type="button" 
              class="page-btn page-next" 
              :disabled="currentPage >= totalPages"
              @click="goToNextPage"
            >
              下一页
            </button>
          </div>
          
          <!-- 页码跳转 -->
          <div class="page-jumper">
            <span>前往</span>
            <input 
              type="number" 
              v-model.number="jumpToPageNumber"
              min="1" 
              :max="totalPages"
              class="page-jump-input"
              @keyup.enter="jumpToPage"
            />
            <span>页</span>
            <button type="button" class="page-btn page-jump-btn" @click="jumpToPage">
              确定
            </button>
          </div>
        </div>
      </div>
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="userDetailDialogVisible"
      title="用户详情"
      width="50%"
      :close-on-click-modal="false"
    >
      <div v-if="currentUser" class="user-detail-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户ID">{{ safeCurrentUser.id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ safeCurrentUser.username || '-' }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ safeCurrentUser.realName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ safeCurrentUser.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ safeCurrentUser.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ safeCurrentUser.department || '-' }}</el-descriptions-item>
          <el-descriptions-item label="角色">{{ safeCurrentUser.roleId === 2 ? '管理员' : '普通用户' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="safeCurrentUser.status === '1' ? 'success' : 'danger'">
              {{ safeCurrentUser.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(safeCurrentUser.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="登录次数">{{ safeCurrentUser.loginCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="最后登录时间">{{ formatDate(safeCurrentUser.lastLoginTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ safeCurrentUser.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="empty-state">
        <p>加载中...</p>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" disabled>
          <el-input v-model="resetPasswordForm.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPasswordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPassword">确定重置</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加用户"
      width="500px"
      @close="resetAddForm"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="addForm.roleId" placeholder="选择角色">
            <el-option label="普通用户" value="1" />
            <el-option label="管理员" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addForm.status" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="addForm.remark" 
            placeholder="请输入备注信息" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAddUserDialog">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="500px"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="editForm.roleId" placeholder="选择角色">
            <el-option label="普通用户" value="1" />
            <el-option label="管理员" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="editForm.status" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="修改密码">
          <el-checkbox v-model="changePassword">是否修改密码</el-checkbox>
          <el-input 
            v-if="changePassword"
            v-model="editForm.password" 
            type="password" 
            placeholder="请输入新密码" 
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            placeholder="请输入备注信息" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<style lang="scss" scoped>
/* 合并的样式定义 */
.admin-users-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 40px);
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  padding: 20px;
  
  .header-content {
    .breadcrumb {
      color: #606266;
      font-size: 14px;
      margin-top: 8px;
      
      .current {
        color: #409eff;
        font-weight: 500;
      }
    }
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
}

/* 搜索筛选卡片样式 */
.search-filter-card {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  padding: 20px;
  margin-bottom: 20px;
  width: 100%;
  overflow-x: auto;
  box-sizing: border-box;
  
  .search-form {
    .el-form-item {
      margin-right: 10px;
    }
  }
}

/* 批量操作工具栏样式 */
.batch-operations {
  margin-bottom: 20px;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 数据表格卡片样式 */
.data-table-card {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  padding: 20px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto;
}

/* 自定义表格样式 */
.custom-table-wrapper {
  width: 99%;
  min-width: 1200px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s;
  
  &:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
  }
}

/* 表头样式 - 固定在顶部 */
.custom-table-header {
  background-color: #fafafa;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 表格内容区 - 可滚动 */
.custom-table-body {
  max-height: calc(100vh - 400px); /* 调整为合适的高度 */
  overflow-y: auto;
  position: relative;
  /* 美化滚动条 */
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
    transition: background 0.3s;
    
    &:hover {
      background: #a8a8a8;
    }
  }
}

/* 自定义表格行样式 */
.custom-table-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e4e7ed;
  transition: all 0.2s;
}

.custom-table-row:hover {
  background-color: #f5f7fa;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.custom-table-row.selected {
  background-color: #ecf5ff;
}

/* 自定义表格单元格样式 */
.custom-table-cell {
  padding: 12px 15px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60px;
  box-sizing: border-box;
  word-break: break-word;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: all 0.2s;
}

.custom-table-cell:last-child {
  border-right: none;
  position: sticky;
  right: 0;
  background-color: rgba(255, 255, 255, 0.95);
  z-index: 5;
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .custom-table-wrapper {
    min-width: 900px;
  }
  
  .custom-table-cell {
    font-size: 13px;
    padding: 10px 12px;
  }
  
  .hidden-mobile {
    display: none;
  }
}

@media screen and (max-width: 768px) {
  /* 移动设备优化 */
  .custom-table-wrapper {
    min-width: auto;
    border-radius: 4px;
  }
  
  .custom-table-cell {
    font-size: 12px;
    padding: 8px 10px;
  }
  
  /* 移动端表格优化 */
  .custom-table-row {
    position: relative;
    
    &:hover {
      transform: none;
      box-shadow: none;
    }
  }
  
  .operation-buttons {
    flex-direction: column;
    align-items: stretch;
  }
}

/* 深色模式适配 */
.dark-theme {
  .custom-table-wrapper {
    border-color: #404040;
    background-color: #202020;
  }
  
  .custom-table-header {
    background-color: #303030;
  }
  
  .custom-table-row {
    border-bottom-color: #404040;
    
    &:hover {
      background-color: #303030;
    }
    
    &.selected {
      background-color: #1a365d;
    }
  }
  
  .custom-table-cell {
    border-right-color: #404040;
    color: #e0e0e0;
    
    &:last-child {
      background-color: rgba(32, 32, 32, 0.95);
    }
  }
}

/* 复选框样式 */
.select-all-checkbox, .row-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 角色标签样式 */
.role-tag {
  width: 80px;
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
}

.role-tag.admin {
  background-color: #409eff;
}

.role-tag.user {
  background-color: #67c23a;
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 20px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

input:checked + .slider {
  background-color: #67c23a;
}

input:checked + .slider:before {
  transform: translateX(20px);
}

.switch:active .slider:before {
  width: 20px;
}

input:checked + .switch:active .slider:before {
  transform: translateX(16px);
}

/* 角色标签样式 */
.role-tag {
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 90px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
}

.role-tag.admin {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: #ffffff;
  border: 1px solid rgba(64, 158, 255, 0.3);
}

.role-tag.user {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: #ffffff;
  border: 1px solid rgba(103, 194, 58, 0.3);
}

.role-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  filter: brightness(1.05);
}

/* 操作按钮样式 */
.operation-btn {
  padding: 4px 12px;
  margin: 0 4px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    color: #409eff;
  }
  
  &.danger-btn {
    border-color: #f56c6c;
    color: #f56c6c;
    
    &:hover {
      background-color: #fef0f0;
    }
  }
  
  &.primary-btn {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
    
    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
  }
}

/* 按钮样式 */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border: 1px solid transparent;
  border-radius: 8px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.btn-primary {
  background-color: #409eff;
  color: #fff;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-success {
  background-color: #67c23a;
  color: #fff;
}

.btn-success:hover {
  background-color: #85ce61;
}

.btn-danger {
  background-color: #f56c6c;
  color: #fff;
}

.btn-danger:hover {
  background-color: #f78989;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-icon {
  margin-right: 4px;
  font-size: 14px;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

/* 表格容器样式优化 */
.table-wrapper {
  overflow-x: auto;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 20px;
  display: block;
}

/* 操作按钮容器样式 */
.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

/* 分页容器样式 */
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding: 15px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.18);
    
    .pagination-info {
      color: #606266;
      font-size: 14px;
    }
  }
  
  /* 自定义分页样式 */
  .custom-pagination {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  
  /* 页码大小选择器 */
  .page-size-selector {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
  }
  
  .page-size-select {
    padding: 4px 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
    font-size: 14px;
    cursor: pointer;
  }
  
  .page-size-select:focus {
    outline: none;
    border-color: #409eff;
  }
  
  /* 分页按钮容器 */
  .pagination-buttons {
    display: flex;
    align-items: center;
    gap: 5px;
  }
  
  /* 页码按钮 */
  .page-btn {
    min-width: 32px;
    height: 32px;
    padding: 0 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
    color: #606266;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .page-btn:hover:not(:disabled) {
    border-color: #409eff;
    color: #409eff;
  }
  
  .page-btn.active {
    border-color: #409eff;
    background-color: #409eff;
    color: #fff;
  }
  
  .page-btn:disabled {
    cursor: not-allowed;
    background-color: #f5f7fa;
    border-color: #dcdfe6;
    color: #c0c4cc;
  }
  
  .page-ellipsis {
    cursor: default;
  }
  
  /* 页码区域 */
  .page-numbers {
    display: flex;
    align-items: center;
  }
  
  /* 页码跳转 */
  .page-jumper {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
  }
  
  .page-jump-input {
    width: 60px;
    height: 32px;
    padding: 0 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
  }
  
  .page-jump-input:focus {
    outline: none;
    border-color: #409eff;
  }
  
  .page-jump-btn {
    padding: 0 10px;
  }

/* 调整按钮样式 */
.el-button {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 调整对话框样式 */
.el-dialog {
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
}

.el-dialog__header {
  border-radius: 16px 16px 0 0;
}

/* 搜索表单样式优化 */
.search-form {
  width: 100%;
  overflow-x: auto;
}

.responsive-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 用户详情样式 */
.user-detail-info {
  padding: 10px;
}

/* 编辑表单中密码提示 */
.password-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}



/* 响应式样式 - 中等屏幕（1024-1440px） */
@media (max-width: 1440px) {
  /* 移除了深度选择器的表格样式 */
}

/* 响应式样式 - 平板屏幕（768-1024px） */
@media (max-width: 1024px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .toolbar .el-input {
    max-width: 100%;
  }
  
  /* 移除了深度选择器的表格样式 */
  
  .el-button {
    padding: 6px 12px;
    font-size: 13px;
  }
}

/* 响应式样式 - 小屏幕（小于768px） */
@media (max-width: 768px) {
  .admin-users-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .search-form {
    width: 100%;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
  
  .search-form .el-form-item__content {
    width: 100%;
  }
  
  .batch-operations {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  /* 隐藏部分列以适应小屏幕 */
  .hidden-mobile {
    display: none;
  }
  
  /* 移除了深度选择器的表格样式 */
  
  /* 操作按钮垂直排列 */
  .operation-buttons {
    flex-direction: column;
    gap: 3px;
  }
  
  .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }
  
  .operation-buttons .el-button span {
    display: none;
  }
  
  /* 移除了深度选择器的表格样式 */
  
  .pagination-container {
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }
}
</style>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Edit, Delete, User, Key, Check, Close } from '@element-plus/icons-vue'
import {
  getUserList,
  getUserDetail,
  addUser,
  updateUser,
  updateUserStatus,
  resetPassword,
  deleteUser,
  batchDeleteUsers,
  batchUpdateUserStatus,
  searchUsers
} from '@/api/user'

// 表格数据相关
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])

// 确保userList和selectedRows的安全访问
const safeUserList = computed(() => userList.value || [])
const safeSelectedRows = computed(() => selectedRows.value || [])

// 计算属性：判断是否全选
const isAllSelected = computed(() => {
  return safeUserList.value.length > 0 && safeSelectedRows.value.length === safeUserList.value.length
})

// 判断行是否被选中
const isRowSelected = (rowId) => {
  return safeSelectedRows.value.some(row => row && row.id === rowId)
}

// 处理行选择
const handleRowSelect = (row) => {
  if (!row || !row.id) return
  const index = safeSelectedRows.value.findIndex(item => item && item.id === row.id)
  if (index > -1) {
    selectedRows.value.splice(index, 1)
  } else {
    selectedRows.value.push(row)
  }
}

// 处理全选
const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedRows.value = [...safeUserList.value]
  } else {
    selectedRows.value = []
  }
}

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  phone: '',
  roleId: '',
  status: ''
})

// 添加用户相关
const addDialogVisible = ref(false)
const addForm = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  realName: '',
  roleId: '1',
  status: '1',
  remark: ''
})
const addFormRef = ref(null)
const addFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  realName: [
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 编辑用户相关
const editDialogVisible = ref(false)
const editForm = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  phone: '',
  realName: '',
  roleId: '1',
  status: '1',
  remark: ''
})
const editFormRef = ref(null)
const changePassword = ref(false)
const editFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  realName: [
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: changePassword.value, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' }
  ]
}

// 用户详情对话框相关
const userDetailDialogVisible = ref(false)
const currentUser = ref(null)

// 重置密码对话框相关
const resetPasswordDialogVisible = ref(false)
const resetPasswordForm = reactive({
  id: '',
  username: '',
  newPassword: '',
  confirmPassword: ''
})
const resetPasswordFormRef = ref(null)
const resetPasswordFormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 生命周期钩子
onMounted(() => {
  // 确保所有响应式数据已初始化
  if (!userList.value) userList.value = []
  if (!selectedRows.value) selectedRows.value = []
  if (!currentUser.value) currentUser.value = {}
  
  // 延迟执行避免初始渲染冲突
  const timer = setTimeout(() => {
    if (!unmounted.value) {
      fetchUserList()
    }
  }, 0)
  
  // 保存定时器ID用于清理
  cleanupTimer.value = timer
})

// 组件卸载时清理
onUnmounted(() => {
  cleanup()
  if (cleanupTimer.value) {
    clearTimeout(cleanupTimer.value)
  }
})

// 组件卸载状态标志
const unmounted = ref(false)
// 加载状态
const loading = ref(false)
// 定时器引用，用于清理
const cleanupTimer = ref(null)

// 获取用户列表
const fetchUserList = async () => {
  // 确保组件未卸载
  if (unmounted.value) return
  
  try {
    loading.value = true
    
    // 安全地获取搜索参数
    const safeSearchForm = searchForm || {}
    const safeCurrentPage = currentPage.value || 1
    const safePageSize = pageSize.value || 10
    
    const response = await getUserList({
      ...safeSearchForm,
      page: safeCurrentPage,
      pageSize: safePageSize
    })
    
    // 确保组件未卸载再更新响应式数据
    if (!unmounted.value) {
      if (response?.data) {
        // 转换状态值为字符串类型，确保前端显示正确
        userList.value = (Array.isArray(response.data.list) ? response.data.list : []).map(user => ({
          ...user,
          status: convertStatusToString(user.status)
        }))
        total.value = Number(response.data.total) || 0
      }
      // 重置选中状态
      selectedRows.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    if (!unmounted.value) {
      ElMessage.error('获取用户列表失败：' + (error?.message || '未知错误'))
      // 失败时使用空数据
      userList.value = []
      total.value = 0
      selectedRows.value = []
    }
  } finally {
    if (!unmounted.value) {
      loading.value = false
    }
  }
}

// 清理函数，组件卸载时调用
const cleanup = () => {
  unmounted.value = true
}

// 搜索用户
const handleSearchUsers = async () => {
  currentPage.value = 1
  try {
    // 使用专门的搜索API进行搜索
    const response = await searchUsers({
      ...searchForm,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (response.data) {
      userList.value = (response.data.list || []).map(user => ({
        ...user,
        status: convertStatusToString(user.status)
      }))
      total.value = response.data.total || 0
    }
  } catch (error) {
    ElMessage.error('搜索用户失败：' + error.message)
    // 失败时回退到获取全部用户列表
    await fetchUserList()
  }
}

// 重置搜索
const resetSearch = async () => {
  // 使用响应式方式重置表单
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  await fetchUserList()
}

// 刷新用户列表
const refreshUserList = async () => {
  await fetchUserList()
}

// 分页处理
const handleSizeChange = async (newSize) => {
  pageSize.value = newSize
  await fetchUserList()
}

const handleCurrentChange = async (newPage) => {
  currentPage.value = newPage
  await fetchUserList()
}

// 选择行处理
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 添加用户对话框
const showAddUserDialog = () => {
  resetAddForm()
  addDialogVisible.value = true
}

const closeAddUserDialog = () => {
  resetAddForm()
  addDialogVisible.value = false
}

const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  Object.assign(addForm, {
    username: '',
    password: '',
    email: '',
    roleId: '1',
    status: '1'
  })
}

// 提交添加用户表单
const submitAddForm = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    
    // 调用添加用户API
    await addUser(addForm)
    
    ElMessage.success('添加用户成功')
    closeAddUserDialog()
    fetchUserList()
  } catch (error) {
    if (error.name === 'ValidationError') {
      return // 表单验证失败，不做处理
    }
    ElMessage.error('添加用户失败：' + error.message)
  }
}

// 编辑用户对话框
const showEditUserDialog = (user) => {
  if (!user || !user.id) {
    ElMessage.warning('无效的用户数据')
    return
  }
  
  Object.assign(editForm, {
    id: user.id,
    username: user.username,
    email: user.email,
    phone: user.phone || '',
    realName: user.realName || '',
    roleId: user.roleId,
    status: convertStatusToString(user.status),
    remark: user.remark || '',
    password: ''
  })
  changePassword.value = false
  editDialogVisible.value = true
}

// 提交编辑用户表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    
    const formData = {
      ...editForm
    }
    
    // 如果不修改密码，删除密码字段
    if (!changePassword.value) {
      delete formData.password
    }
    
    // 调用更新用户API
    await updateUser(formData)
    
    ElMessage.success('编辑用户成功')
    editDialogVisible.value = false
    fetchUserList()
  } catch (error) {
    if (error.name === 'ValidationError') {
      return // 表单验证失败，不做处理
    }
    ElMessage.error('编辑用户失败：' + error.message)
  }
}

// 更新用户状态
const handleUpdateUserStatus = async (userId, status) => {
  if (!userId) {
    ElMessage.warning('无效的用户ID')
    return
  }
  
  try {
    // 调用更新用户状态API
    await updateUserStatus(userId, status)
    
    ElMessage.success('更新状态成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败：' + error.message)
    // 失败时恢复原状态
    fetchUserList()
  }
}

// 删除用户
const handleDeleteUser = (userId) => {
  if (!userId) {
    ElMessage.warning('无效的用户ID')
    return
  }
  ElMessageBox.confirm(
    '确定要删除该用户吗？此操作不可撤销。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用删除用户API
      await deleteUser(userId)
      
      ElMessage.success('删除用户成功')
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败：' + error.message)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除用户
const handleBatchDeleteUsers = async () => {
  const safeSelectedRows = selectedRows.value || []
  if (safeSelectedRows.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${safeSelectedRows.length} 个用户吗？此操作不可撤销`, 
      '警告', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = safeSelectedRows.map(item => item?.id).filter(id => id)
    if (ids.length === 0) {
      ElMessage.warning('未找到有效的用户ID')
      return
    }
    
    // 调用批量删除用户API
    await batchDeleteUsers(ids)
    
    ElMessage.success(`成功删除 ${ids.length} 个用户`)
    selectedRows.value = []
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
    // 用户取消操作
  }
}

// 批量启用/禁用用户
const handleBatchChangeStatus = async (status) => {
  const safeSelectedRows = selectedRows.value || []
  if (safeSelectedRows.length === 0) {
    ElMessage.warning(`请选择要${status === '1' ? '启用' : '禁用'}的用户`)
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要${status === '1' ? '启用' : '禁用'}选中的 ${safeSelectedRows.length} 个用户吗？`, 
      '确认操作', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: status === '0' ? 'warning' : 'info'
      }
    )
    
    const ids = safeSelectedRows.map(item => item?.id).filter(id => id)
    if (ids.length === 0) {
      ElMessage.warning('未找到有效的用户ID')
      return
    }
    
    // 调用批量更新用户状态API
    await batchUpdateUserStatus(ids, status)
    
    ElMessage.success(`成功${status === '1' ? '启用' : '禁用'} ${ids.length} 个用户`)
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量操作失败:', error)
    }
    // 用户取消操作
  }
}

// 查看用户详情
const showUserDetail = async (user) => {
  if (!user || !user.id) {
    ElMessage.warning('无效的用户数据')
    return
  }
  
  try {
    // 调用获取用户详情API
    const response = await getUserDetail(user.id)
    const userData = response?.data || { ...user }
    currentUser.value = {
      ...userData,
      status: convertStatusToString(userData.status)
    }
    userDetailDialogVisible.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
    // 失败时使用传入的用户数据的安全副本
    currentUser.value = {
      ...user,
      status: convertStatusToString(user.status)
    }
    userDetailDialogVisible.value = true
  }
}

// 重置密码
const showResetPasswordDialog = (user) => {
  if (!user || !user.id) {
    ElMessage.warning('无效的用户数据')
    return
  }
  resetPasswordForm.id = user.id
  resetPasswordForm.username = user.username
  resetPasswordForm.newPassword = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordDialogVisible.value = true
}

// 提交重置密码
const submitResetPassword = async () => {
  if (!resetPasswordFormRef.value) return
  
  try {
    await resetPasswordFormRef.value.validate()
    
    // 调用重置密码API
    await resetPassword(resetPasswordForm.id, resetPasswordForm.newPassword)
    
    ElMessage.success('密码重置成功')
    resetPasswordDialogVisible.value = false
    resetPasswordFormRef.value.resetFields()
  } catch (error) {
    if (error.name === 'ValidationError') {
      return // 表单验证失败，不做处理
    }
    ElMessage.error('重置密码失败：' + error.message)
  }
}

// 清空选择
const clearSelection = () => {
  selectedRows.value = []
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'  
  if (typeof date === 'string') return date
  const d = new Date(date)
  if (isNaN(d.getTime())) return '-'  
  return d.toLocaleString('zh-CN')
}

// 转换状态值为字符串，确保前后端类型匹配
const convertStatusToString = (status) => {
  if (status === undefined || status === null) return '0'
  return String(status)
}

// 修复可能的异步渲染问题，确保currentUser和userList在使用前已初始化
const safeCurrentUser = computed(() => currentUser.value || {})
      
      // 跳转页码
  const jumpToPageNumber = ref(1)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 上一页
const goToPreviousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    handleCurrentChange(currentPage.value)
  }
}

// 下一页
const goToNextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    handleCurrentChange(currentPage.value)
  }
}

// 跳转到指定页
const goToPage = (page) => {
  currentPage.value = page
  handleCurrentChange(page)
}

// 页码跳转
const jumpToPage = () => {
  let page = jumpToPageNumber.value
  if (!page || page < 1) {
    page = 1
  } else if (page > totalPages.value) {
    page = totalPages.value
  }
  
  jumpToPageNumber.value = page
  currentPage.value = page
  handleCurrentChange(page)
}

// 生成页码数组
const generatePageNumbers = () => {
  const pages = []
  const total = Number(totalPages.value) || 1 // 确保total是数字且至少为1
  const current = Math.max(1, Math.min(Number(currentPage.value) || 1, total)) // 确保current在有效范围内
  
  // 当总页数小于等于7时，显示所有页码
  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 当总页数大于7时，显示部分页码
    if (current <= 4) {
      // 当前页在前面
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后面
      pages.push(1)
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }
  return pages
}
</script>
